package com.yand.thinkingInJava.thinkingInJava21.threadNewcomponent;



import java.util.concurrent.Exchanger;

class ExchangerProducer implements Runnable{

   private Exchanger<String> exchanger;

   private String str;

   private String threadName;

    public ExchangerProducer(Exchanger<String> exchanger, String str, String threadName) {
        this.exchanger = exchanger;
        this.str = str;
        this.threadName = threadName;
    }

    @Override
    public void run() {
        try {
            System.out.println(threadName +":"+exchanger.exchange(str));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

/**
 * exchanger 是2个任务之间交换对象的栅栏
 * 用于交换2个线程之间的对象
 */
public class ExchangerDemo {

    public static void main(String [] args){
        Exchanger<String> exchanger = new Exchanger<>();
        Thread t1  = new Thread(new ExchangerProducer(exchanger, "yand","thread1"));
        Thread t2  = new Thread(new ExchangerProducer(exchanger, "zq","thread2"));
        t1.start();
        t2.start();
    }

}
